#include <QDebug>
#include <QtWidgets/QFileDialog>
#include "core/expressionsimplifier.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _simplifier(nullptr)
  {
  ui->setupUi(this);

  bool fileLogging = true;
  QString defaultConfigPath = "";

#if defined(DEBUG)
  fileLogging = false;
  defaultConfigPath = "../config.xml";
#else
  defaultConfigPath = "config.xml";
#endif

  _simplifier = new ExpressionSimplifier(fileLogging, defaultConfigPath);
  this->setWindowTitle("Using NCACore " + _simplifier->getVersion());
  connect(_simplifier, SIGNAL(error(QString)), this, SLOT(showError(QString)), Qt::QueuedConnection);     // this worked on Windows, Qt5.1.1

  connect(ui->txtExpression, SIGNAL(returnPressed()), ui->pbParse, SLOT(click()));
  ui->pbClearLog->setText("Clear");
  }

MainWindow::~MainWindow()
  {  
  delete _simplifier;
  delete ui;
  }

void MainWindow::on_txtExpression_textChanged()
  {
  }

void MainWindow::on_pbParse_clicked()
  {    
  _simplifier->setExpFromString(ui->txtExpression->text().trimmed());
  ui->txtLog->append("Working on: " + _simplifier->getExp() + "\n");

  QStringList qsl = _simplifier->simplify();

  for (int i = 0; i < qsl.size(); i++)
    ui->txtLog->append(QString::number(i) + ": " + qsl[i] + "");
  ui->txtLog->append("\n\n");
  }

void MainWindow::on_pbLoadConfig_clicked()
  {
  QString fileName = QFileDialog::getOpenFileName(this, tr("Open config"),
                                                  ".",
                                                  tr("Config file (*.xml)"));
  if (fileName.isEmpty())
    {
    statusBar()->showMessage(tr("Opening config file failed"));
    return;
    }

  _simplifier->loadConfig(fileName);
  }

void MainWindow::on_pbClearLog_clicked()
  {  
  ui->txtLog->clear();
  }

void MainWindow::showError(QString msg)
  {
  statusBar()->setStyleSheet("QStatusBar { color: red;}");
  statusBar()->showMessage(msg);

  QTimer::singleShot(5000, Qt::VeryCoarseTimer, this, SLOT(clearStatusBarColor()));
  }

void MainWindow::clearStatusBarColor()
  {
  statusBar()->setStyleSheet("");
  }
